package a_doubleWrite;

import java.util.*;

/**
 * todo
 *
 * @author luolidong
 * @version 1.0
 * @create 2021-08-01 09:35
 */
public class L224 {
    public int calculate(String s) {
        Deque<String> op_stack = new ArrayDeque<>();
        List<String> list = new ArrayList<>();
        String s2 = s.trim().replaceAll(" ", "");
        char[] chars = s2.toCharArray();

        for (int i=0;i<chars.length;i++) {
            if (Character.isDigit(chars[i])) {
                int num = 0;
                while (i < chars.length && Character.isDigit(chars[i])) {
                    num = num * 10 + chars[i] - '0';
                    i++;
                }
                list.add(num + "");
                //一定要i--;因为i++后下面else不执行
                i--;
            } else if (chars[i]=='(') {
                op_stack.push(chars[i]+"");
            } else if (chars[i]==')') {
                while (!op_stack.isEmpty()&&!op_stack.peek().equals("(")) {
                    list.add(op_stack.pop());
                }
                op_stack.pop();
            } else {
                while (!op_stack.isEmpty() && !op_stack.peek().equals("(")) {
                    list.add(op_stack.pop());
                }
                op_stack.push(chars[i]+"");
            }

        }
        //后缀表达式
        while (!op_stack.isEmpty()){
            list.add(op_stack.pop());
        }
        list.forEach(System.out::println);
        //输出,后缀表达式求值
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < list.size(); i++) {
            String s1 = list.get(i);
            if (s1.equals("+") || s1.equals("-")) {
                Integer pop = stack.pop();
                Integer pop1 = stack.pop();
                stack.push(doNums(pop1, pop, s1));
            } else {
                stack.push(Integer.parseInt(s1));
            }
        }
        return stack.pop();
    }

    public int doNums(int n1, int n2, String str) {
        switch (str) {
            case "+":
                return n1 + n2;
            case "-":
                return n1 - n2;
//            case "*": return n1*n2;
//            case "/": return n1/n2;
        }
        return 0;
    }

    public static void main(String[] args) {
        L224 l224 = new L224();
        int calculate = l224.calculate("(1+(4+5+2)-3)+(6+8)");
        System.out.println(calculate);
    }
}
